#import "PAThumbWheelCell.h"
//#import "PAThumbWheelCellDrawing.h" // stuck this functionality in here...
#import "PAThumbWheel.h"

/******************************************************************************
	PAThumbWheelCell
	
PAThumbWheel offers the functionality of Slider plus the features that you would expect from a real thumbwheel (including 2 3/4 D Graphics!).

PAThumbWheel has a linear display mode and a radial display mode and offers the ability to assign a value to the visible region of the control as well as an absolute value that the ThumbWheel will either ignore, bound to or wrap around.

PAThumbWheel can also return relative values via its -relativeIntValue & -relativeFloatValue methods. A snap back option allows mouse loops to start from and return to a base value.

Copyright 1992, Jeff Martin. (jmartin@next.com 415-780-3833)
******************************************************************************/
#define PI			3.141592654
#define HALF_PI		1.570796327
#define DEG_TO_RAD 0.0174532925199433		//  PI/180.0
#define SIN(x) (sin(DEG_TO_RAD*(x)))
#define COS(x) (cos(DEG_TO_RAD*(x)))
#define TAN(x) (tan(DEG_TO_RAD*(x)))

#define RAD_TO_DEG 57.295779513082320876	//  180.0/PI
#define ASIN(x) (asin(x)*RAD_TO_DEG)
#define ACOS(x) (acos(x)*RAD_TO_DEG)
#define ATAN(x) (atan(x)*RAD_TO_DEG)
// A mod function for floating values
#define MOD(x,y) ((x) - (y)*(int)((float)(x)/(y)))
// Keep 'a' between x and y
#define CLAMP(a,x,y) (MAX((x), MIN((y), (a))))
// Keep 'a' between 'x' and 'y' by wrapping it to the other side
#define CLAMP_WITH_WRAP(a,x,y)  											\
( ((a) < (x)) ? ((y) - MOD(((x)-(a)),((y)-(x)))) : 						\
( ((a) > (y)) ? ((x) + MOD(((a)-(y)),((y)-(x)))) : (a) ) )
// Is a between x and y
#define ISBETWEEN(a,x,y) (((a)>=(x))&&((a)<=(y)))
#define EQUAL(a,b) (ABS((a)-(b))<0.00001)

@implementation PAThumbWheelCell

// Set reasonable defaults
- init
{
	[super init];
	[self setType:NX_TEXTCELL];
	[self setHorizontal];

	[self setLinear]; [self setUnbounded];
	[self setVisibleMax:1.0]; [self setVisibleMin:-1.0];
	[self setAbsoluteMax:2.0]; [self setAbsoluteMin:-2.0];
	[self setSnapsBack:YES]; [self setSnapBackValue:0.0];
	[self setDashInterval:10]; [self setShowMainDash:YES];
	[self setColor:NX_COLORLTGRAY];
	
	[self sendActionOn:NX_MOUSEDOWNMASK|NX_MOUSEDRAGGEDMASK|NX_MOUSEUPMASK];
        colorChanged = NO;

	return self;
}

- awake
{  colorChanged = NO;
   return [super awake];
}

- copyFromZone:(NXZone *)zone
{
  id newCopy = [super copyFromZone:zone];

  return newCopy;
}


// Override trackMouse to provide an infinitely large area(continuous tracking)
- (BOOL)trackMouse:(NXEvent *)event inRect:(const NXRect *)rect ofView:view
{ cellFrame = *rect; return [super trackMouse:event inRect:NULL ofView:view]; }

// Override to return YES (always track mouse)
- (BOOL)startTrackingAt:(const NXPoint *)startPoint inView:aView { return YES;}

// Override from cell to track mouse
- (BOOL)continueTracking:(const NXPoint *)lastPoint 
    at:(const NXPoint *)currPoint inView:view
{
	float currPointVal =[self floatValueAtPoint:*currPoint forFrame:cellFrame];
	float lastPointVal =[self floatValueAtPoint:*lastPoint forFrame:cellFrame];
	float mouseScale = ([NXApp currentEvent]->flags&NX_ALTERNATEMASK)? .1 : 1;
	
	// If TW is bounded and at absolute bound, only track when mouse comes back
	if([self isBounded]) {
		// Return if we are already at absoluteMax and currPoint is greater
		if(EQUAL([self floatValue], [self absoluteMax])) {
			if(currPointVal > [self absoluteMax]) return YES;
			else lastPointVal = [self absoluteMax];
		}
		// Return if we are already at absoluteMin and currPoint is less
		if(EQUAL([self floatValue], [self absoluteMin])) {
			if(currPointVal < [self absoluteMin]) return YES;
			else lastPointVal = [self absoluteMin];
		}
	}
	
	// Set the float value relative to last point
	[self setFloatValue:[self floatValue] + 
		(currPointVal - lastPointVal)*mouseScale];
	
	// Redraw control
	[view display];
	return YES;	// Always continue to track mouse
}


/******************************************************************************
	floatValueAtPoint:forFrame:
	
	This method gives the value that corresponds to a point with respect to the given frame and the visible range. When in radial mode, the point on the thumbwheel is approximated with a power series for arcCos to get legal values for points outside of the frame.
******************************************************************************/
- (float)floatValueAtPoint:(NXPoint)point forFrame:(NXRect)frame
{
	float pos = [self isVertical] ? point.y : point.x;
	float base = [self isVertical] ? NX_Y(&frame) : NX_X(&frame);
	float width = [self isVertical] ? NX_HEIGHT(&frame) : NX_WIDTH(&frame);
	float value;
	
	if([self isLinear])
		value = [self visibleMin] + (pos - base)/width*[self visibleRange];
	else {
		float radius = width/2;
		float midP = base + radius;
		float x = (midP - pos)/radius;
		// Get degrees by pwr series approximation of ArcCos (Pi/2 - x - x^3/6)
		float alpha = (HALF_PI - x - x*x*x/6);
		// Convert degrees to TW coords
		value = [self visibleMin] + alpha/PI*[self visibleRange];
	}
	return value;
}
	
// Override from cell to snapback if neccessary
- stopTracking:(const NXPoint *)lastPoint at:(const NXPoint *)stopPoint
    inView:view mouseIsUp:(BOOL)flag
{
	// If the ThumbWheel is in snap back mode, snap it back and redraw
	if([self snapsBack]) {
		[self setFloatValue:[self snapBackValue]];
		[self resetRelativeValue];
		[view display];
	}
	return [super stopTracking:lastPoint at:stopPoint inView:view 
		mouseIsUp:flag];
}

// Direction is either DIRECTION_HORIZONTAL or DIRECTION_VERTICAL
- (int)direction { return direction; }
- setDirection:(int)dir
{ direction = dir; [image free]; image = NULL; return self; }
- (BOOL)isVertical { return direction == DIRECTION_VERTICAL; }
- setVertical { direction = DIRECTION_VERTICAL; return self; }
- (BOOL)isHorizontal { return direction == DIRECTION_HORIZONTAL; }
- setHorizontal { direction = DIRECTION_HORIZONTAL; return self; }

/******************************************************************************
	displayMode, setDisplayMode
	
	The displayMode is either DISPLAY_MODE_LINEAR or DISPLAY_MODE_RADIAL. Linear displays a flat ruler type control whereas radial displays a 3D thumbwheel that actually looks curved .
******************************************************************************/
- (int)displayMode { return displayMode; }
- setDisplayMode:(int)mode { displayMode = mode; return self; }
- (BOOL)isRadial { return displayMode == DISPLAY_MODE_RADIAL; }
- setRadial { return [self setDisplayMode:DISPLAY_MODE_RADIAL]; }
- (BOOL)isLinear { return displayMode == DISPLAY_MODE_LINEAR; }
- setLinear { return [self setDisplayMode:DISPLAY_MODE_LINEAR]; }

/******************************************************************************
	intValue, setIntValue, floatValue, setFloatValue
	
	These methods are overridden to allow us to calculate relative values and to constrain the value with respect to the absolute mode and absolute values.
******************************************************************************/
- (int)intValue { return (int)[self floatValue]; }
- setIntValue:(int)val { [self setFloatValue:val]; return self; }
- (float)floatValue { return floatValue; }
- setFloatValue:(float)val
{ 
	// Clamp or Wrap newValue wrt the absoluteMode
	if(!ISBETWEEN(val, [self absoluteMin], [self absoluteMax])) {
		if([self isBounded]) val = 
			CLAMP(val, [self absoluteMin], [self absoluteMax]);
		else if([self isWrapped]) val = 
			CLAMP_WITH_WRAP(val, [self absoluteMin], [self absoluteMax]);
	}

	// Store last float value and set float value
	lastFloatValue = floatValue; floatValue = val;
	return self;
}
- (float)lastFloatValue { return lastFloatValue; }
- setLastFloatValue:(float)value { lastFloatValue=value; return self;}

/******************************************************************************
	visibleMax, visibleMin, visibleRange, middleValue
	
	VisibleMax and visibleMin are the values of the thumbwheel at either end; max value is at right/top, min is at left/bottom. middleValue is the value of the TW at the center (wrt visibleMin and visibleMax).
******************************************************************************/
- (float)visibleMax { return visMax; }
- setVisibleMax:(float)max { visMax = max; return self; }
- (float)visibleMin { return visMin; }
- setVisibleMin:(float)min { visMin = min; return self; }
- (float)visibleRange { return [self visibleMax] - [self visibleMin]; }
- (float)middleValue { return [self visibleMin] + [self visibleRange]/2; }

/******************************************************************************
	absoluteMode, absoluteMax, absoluteMin
	
	The absolute mode refers to ThumbWheel values that exceed the visible range. ABSOLUTE_UNBOUNDED means that the TW can be dragged as high or low as desired. ABSOLUTE_BOUNDED means that the TW will be clamped to some arbitrarily large value. ABSOLUTE_WRAPPED means that the TW will wrap from the absoluteMax to the absoluteMin (and vise-versa) when applicable. AbsoluteMax is the value off to the right and up. AbsoluteMin us the value off to the left and down.
******************************************************************************/
- (int)absoluteMode		{ return absMode; }
- setAbsoluteMode:(int)mode { absMode = mode; return self; }
- (BOOL)isUnbounded		{ return absMode == ABSOLUTE_UNBOUNDED;  }
- setUnbounded			{ return [self setAbsoluteMode:ABSOLUTE_UNBOUNDED]; }
- (BOOL)isBounded 		{ return absMode == ABSOLUTE_BOUNDED; }
- setBounded			{ return [self setAbsoluteMode:ABSOLUTE_BOUNDED]; }
- (BOOL)isWrapped		{ return absMode == ABSOLUTE_WRAPPED; }
- setWrapped			{ return [self setAbsoluteMode:ABSOLUTE_WRAPPED]; }
- (float)absoluteMax	{ return absMax; }
- setAbsoluteMax:(float)value { absMax = value; return self; }
- (float)absoluteMin 	{ return absMin; }
- setAbsoluteMin:(float)value { absMin = value; return self; }
- (float)absoluteRange	{ return [self absoluteMax] - [self absoluteMin]; }

/******************************************************************************
	relativeIntValue, relativeFloatValue, resetRelativeValue
	
	These two methods return the change of the value since the last iteration. This is useful for a relative method call ( rotateBy: as opposed to rotateTo:). resetRelativeValue sets the relative change to zero (typically only called internally when snapping back).
******************************************************************************/
- (int)relativeIntValue
{ return [self intValue] - (int)[self lastFloatValue];}
- (float)relativeFloatValue
{ return [self floatValue] - [self lastFloatValue]; }
- resetRelativeValue { [self setLastFloatValue:[self floatValue]];return self;}

/******************************************************************************
	snapsBack, snapBackValue
	
	It is sometimes useful to have the thumbwheel snap back to some value (zero by default) so that it can be used for relative modification of values (rotate by as opposed to rotateTo:).
******************************************************************************/
- (BOOL)snapsBack				{ return snapsBack; }
- setSnapsBack:(BOOL)flag		{ snapsBack = flag; return self; }
- (float)snapBackValue			{return snapBackValue; }
- setSnapBackValue:(float)value	{ snapBackValue = value;return self;}

/******************************************************************************
	dashInterval, setDashInterval, setDashIntervalEqual

	 The dash interval is either in degrees (DISPLAY_MODE_RADIAL) or PostScript 
points (DISPLAY_MODE_LINEAR). The default is 10 of each.
******************************************************************************/
- (float)dashInterval			{ return dashInterval; }
- setDashInterval:(float)val
{ 
  // wave fixed this.  This was a crasher...
  if (val < 1.0) 
  {  dashInterval = 1.0;
  } 
  else
  {  dashInterval = val;
  }
  return self; 
}

/******************************************************************************
	showMainDash, setShowMainDash

	 The main dash is the dash in the center of the control and gives feedback as to the absolute value of the control. This should be set to NO for TW that only provide relative values.
******************************************************************************/
- (BOOL)showMainDash 			{return showMainDash;}
- setShowMainDash:(BOOL)flag	{ showMainDash = flag; return self; }

/******************************************************************************
	color, setColor

	 These methods manipulate the predominant color of the ThumbWheel. Radial ThumbWheel are of course shades of these. The default is NX_COLORLTGRAY. 
******************************************************************************/
- (NXColor)color			{return color;}
- setColor:(NXColor)c		{ color = c; return self; }

/******************************************************************************
	shift
	
	 The shift is how much the dashes are shifted by to achieve the animation of motion it is in points. It is calculated from the visibleRange and the physicalRange (frame).
******************************************************************************/
- (int)shift:(const NXRect *)frame
{	
	if([self isLinear]) {
		if([self isHorizontal])
			return (int)(([self floatValue] - [self visibleMin]) / 
				[self visibleRange]*NX_WIDTH(frame) + .5);
		else
			return (int)(([self floatValue] - [self visibleMin]) / 
				[self visibleRange]*NX_HEIGHT(frame) +.5);
	}
	else return (int)(([self floatValue] - [self visibleMin])/ 
		[self visibleRange]*180 + .5);
}

// Override highlight:inView:lit: so that it does nothing
- highlight:(const NXRect *)frame inView:view lit:(BOOL)flag { return self; }

// Override this so that we track mouse whether or not it is on top of us.
+ (BOOL)prefersTrackingUntilMouseUp { return YES; }



/******************************************************************************

	 The Read and Write Methods are for archival.
******************************************************************************/
- write:(NXTypedStream *)stream
{
	[super write:stream];

	NXWriteType(stream, "i", &displayMode);
	NXWriteType(stream, "i", &direction);

	NXWriteType(stream, "f", &floatValue);
	NXWriteType(stream, "f", &lastFloatValue);

	NXWriteType(stream, "f", &visMax);
	NXWriteType(stream, "f", &visMin);

	NXWriteType(stream, "i", &absMode);
	NXWriteType(stream, "f", &absMax);
	NXWriteType(stream, "f", &absMin);

	NXWriteType(stream, "c", &snapsBack);
	NXWriteType(stream, "f", &snapBackValue);

	NXWriteType(stream, "i", &dashInterval);
	NXWriteType(stream, "c", &showMainDash);

	NXWriteColor(stream, color);
	return self;
}

- read:(NXTypedStream *)stream
{
	[super read:stream];

	NXReadType(stream, "i", &displayMode);
	NXReadType(stream, "i", &direction);


	NXReadType(stream, "f", &floatValue);
	NXReadType(stream, "f", &lastFloatValue);

	NXReadType(stream, "f", &visMax);
	NXReadType(stream, "f", &visMin);

	NXReadType(stream, "i", &absMode);
	NXReadType(stream, "f", &absMax);
	NXReadType(stream, "f", &absMin);

	NXReadType(stream, "c", &snapsBack);
	NXReadType(stream, "f", &snapBackValue);

	NXReadType(stream, "i", &dashInterval);
	NXReadType(stream, "c", &showMainDash);

	color = NXReadColor(stream);
        colorChanged = YES;
	return self;
}

- free
{
	[image free];
	return [super free];
}

// stuff stolen from PAThumbWheelCellDrawing

#define NOTEQUAL(a,b) (ABS((a)-(b))>0.0001)
#define EVEN(x) (!(((int)(x))%2))

- drawSelf:(const NXRect *)theFrame inView:view
{
	NXRect frame = *theFrame;
	float *pnts;						// Used for user path of dashes
	char *ops;							// Used for user path of dashes
	int pntCount, opCount;				// Used for user path of dashes
	float bbox[4] = { NX_X(theFrame), NX_Y(theFrame),
		NX_MAXX(theFrame), NX_MAXY(theFrame) };
	
	// Inset by two to allow for bezeled border
	NXInsetRect(&frame,2,2);

	// Draw the background
	if([self isLinear]) {
		NXDrawGrayBezel(theFrame, theFrame);
		NXSetColor(color);
		NXRectFill(&frame);
	}
	else { // if([self isRadial])
		NXSize imageSize;
		[image getSize:&imageSize];
		if(NOTEQUAL(imageSize.width,NX_WIDTH(theFrame)) ||
			NOTEQUAL(imageSize.height,NX_HEIGHT(theFrame)) || colorChanged)
			[self generateImage:theFrame];
		[image composite:NX_COPY toPoint:&theFrame->origin];
	}
	
	// Get the userpath for the dashes
	[self getDashesForFrame:&frame :&pnts :&pntCount :&ops :&opCount];

	// Draw dashes once for white part of groove
	if([self isHorizontal]) PStranslate(1,0); else PStranslate(0,-1);

	// Draw linear white dashes
	if([self isLinear]) {
		NXSetColor(PAScaleRGBColor(color, 1.5));
		DPSDoUserPath(pnts, pntCount, dps_float, ops, opCount, bbox, 
			dps_ustroke);
	}
	
	// Break up radial white dashes to fade a little bit at ends
	else {
		int i = 0, j = 0, d = [self isHorizontal]? 0 : 1;
		float oneQuarterOfX = [self isHorizontal]? (NX_X(&frame) + 
			NX_WIDTH(&frame)/4) : (NX_Y(&frame) + NX_HEIGHT(&frame)/4);
		float threeQuartersOfX =[self isHorizontal]? (NX_X(&frame) + 
			3*NX_WIDTH(&frame)/4) : (NX_Y(&frame) + 3*NX_HEIGHT(&frame)/4);

		NXSetColor(color);
		while((i < pntCount) && (pnts[i+d] < oneQuarterOfX)) i += 4; j = i;
		if(i>0) DPSDoUserPath(pnts, i, dps_float, ops, i/2, bbox, dps_ustroke);
	
		NXSetColor(PAScaleRGBColor(color, 1.5));
		while((j < pntCount) && (pnts[j+d] < threeQuartersOfX)) j+=4;
		if(j>i) DPSDoUserPath(&pnts[i], j-i, dps_float, &ops[i/2], j/2-i/2,
			bbox, dps_ustroke);
	
		NXSetColor(color);
		if(pntCount>j) DPSDoUserPath(&pnts[j], pntCount-j, dps_float, 
			&ops[j/2], opCount-j/2, bbox, dps_ustroke);
	}
	
	if([self isHorizontal]) PStranslate(-1,0); else PStranslate(0,1);

	// Draw again for dark part of groove
	if([self isLinear]) NXSetColor(PAScaleRGBColor(color, .5)); 
	else NXSetColor(NX_COLORBLACK);
	DPSDoUserPath(pnts, pntCount, dps_float, ops, opCount, bbox, dps_ustroke);
	
	// If disabled then dim ThumbWheel out
	if(![self isEnabled]) {
		NXSetColor(NX_COLORWHITE); PSsetalpha(.5);
		PScompositerect(NX_X(&frame), NX_Y(&frame), NX_WIDTH(&frame),
			NX_HEIGHT(&frame), NX_SOVER);
	}
	
	// Free user path variables
	free(pnts); free(ops);
	return self;
}


// wave added these two routines...
- setColorChanged:(BOOL)flag { colorChanged = flag;  return self; }
- (BOOL)colorChanged { return colorChanged; }


- getDashesForFrame:(const NXRect *)frame :(float **)PNTS :(int *)PNTCOUNT :(char **)OPS :(int *)OPCOUNT
{
	// Get dashInterval and shift
	int dashInt = [self dashInterval];
	int shift = [self shift:frame];

	// Calculate how many dashes there will be and alloc space for pnts and ops
	int dashCount = 2 + ([self isRadial] ? 180/dashInt : 
		([self isVertical] ? NX_HEIGHT(frame) : NX_WIDTH(frame)) / dashInt);
	float *pnts = malloc(sizeof(float)*dashCount*4); // (moveto+lineto)*(x+y)=4
	char *ops 	= malloc(sizeof(char)*dashCount*2);  // (moveto+lineto) = 2
	int i=0, j=0;
	
	// Calculate dash sizes
	int dashBase 	= [self isVertical] ? NX_X(frame) : NX_Y(frame);
	int dashHeight	= [self isVertical] ? NX_WIDTH(frame) : NX_HEIGHT(frame);
	int dashMinTop 	= dashBase + dashHeight*.25;
	int dashMajTop 	= dashBase + dashHeight*.5;
	int dashTop		= dashBase + dashHeight;
	
	float base		=	[self isVertical] ? NX_Y(frame) : NX_X(frame);
	float width		=	[self isVertical]? NX_HEIGHT(frame) : NX_WIDTH(frame);
	float halfWidth	=	width/2;
	float mid		=	base + halfWidth;
	float top		=	base + width;

	float mainDash;
	float x;
	
	// Calculate whether first dash is a major one. 
	BOOL isMajor	= (shift>=0)? EVEN(shift/dashInt) : !EVEN(shift/dashInt);
		
	// Calculate Linear dashes
	if([self isLinear]) {
		// Set Main dash
		mainDash = base + shift;

		// Calculate starting point and set the dashes
		x = base+CLAMP_WITH_WRAP(shift,0,dashInt)%((shift>=0)? dashInt:999999);
		if([self isVertical]) while(x<top) {
			pnts[i++] = dashBase; pnts[i++] = x;
			pnts[i++] = isMajor ? dashMajTop : dashMinTop;
			if(EQUAL(x, mainDash)&&[self showMainDash]) pnts[i-1] = dashTop;
			pnts[i++] = x;
			x += dashInt; isMajor = !isMajor;
		}
		else while(x<top) {
			pnts[i++] = x; pnts[i++] = dashBase;
			pnts[i++] = x; pnts[i++] = isMajor ? dashMajTop : dashMinTop;
			if(EQUAL(x, mainDash)&&[self showMainDash]) pnts[i-1] = dashTop;
			x += dashInt; isMajor = !isMajor;
		}
	}

	// Calculate Radial Dashes
	else {
		// This is used to convert the degrees of a dash to a location(in pnts)
		float linDash = 0;
		
		// Inset dash size for beveled edges
		dashBase++; dashTop--;
		
		// Calc Main dash if we show it and it is in sight
		mainDash = mid - IntCos(shift)*halfWidth;

		// Calculate the starting point and set the dashes
		x = CLAMP_WITH_WRAP(shift, 0, dashInt)%((shift>=0)? dashInt:999999);
		if([self isVertical]) while(x<180) {
			linDash = mid - IntCos(x)*halfWidth;
			pnts[i++] = dashBase; pnts[i++] = linDash;
			pnts[i++] = isMajor ? dashMajTop : dashMinTop;
			// Check to see if this is a valid main dash
			if(isMajor && EQUAL(linDash,mainDash) && [self showMainDash] &&
				ISBETWEEN(shift, 0, 180)) pnts[i-1]=dashTop;
			pnts[i++] = linDash;
			x += dashInt; isMajor = !isMajor;
		}
		else while(x<180) {
			linDash = mid - IntCos(x)*halfWidth;
			pnts[i++] = linDash; pnts[i++] = dashBase;
			pnts[i++] = linDash; pnts[i++] = isMajor ? dashMajTop : dashMinTop;
			// Check to see if this is a valid main dash
			if(isMajor && EQUAL(linDash,mainDash) && [self showMainDash] &&
				ISBETWEEN(shift, 0, 180)) pnts[i-1]=dashTop;
			x += dashInt; isMajor = !isMajor;
		}
	}
		
	// fill the ops array with dps_moveto and dps_lineto
	while(j<i/2) { ops[j++] = dps_moveto; ops[j++] = dps_lineto; }
	 
	// Set the passed in pointers to the arrays and the counts and return
	*PNTS = pnts; *OPS = ops; *PNTCOUNT = i; *OPCOUNT = j;
	return self;
}

- generateImage:(const NXRect *)theFrame
{
	float circleHeight;
	float x, rad, rad2, mid;
	NXRect frame = *theFrame;

	if(!image) image = [[NXImage alloc] init];
	[image setSize:&frame.size];
	[image lockFocus];
	NXDrawGrayBezel(&frame,&frame);
	NXInsetRect(&frame,2,2);
	PSsetlinewidth(0.0); 

	// Draw horizonal version
	if(direction == DIRECTION_HORIZONTAL) {
		rad = NX_WIDTH(&frame)/2.0; rad2 = rad*rad;
		mid = NX_MIDX(&frame);

		for(x = NX_X(&frame); x <= NX_MIDX(&frame); x++) {
			float topx = NX_MAXX(&frame) - (x - NX_X(&frame));
			circleHeight = sqrt(rad2 - (mid-x)*(mid-x))/rad;

			PSnewpath();
			NXSetColor(PAScaleRGBColor(color, .5*circleHeight));
			PSmoveto(x, NX_Y(&frame));		PSlineto(x, NX_Y(&frame) + 2);
			PSmoveto(topx, NX_Y(&frame));	PSlineto(topx, NX_Y(&frame) + 2);
			PSstroke();

			PSnewpath();
			NXSetColor(PAScaleRGBColor(color, circleHeight));
			PSmoveto(x, NX_Y(&frame)+2);	PSlineto(x, NX_MAXY(&frame) - 1);
			PSmoveto(topx, NX_Y(&frame)+2);PSlineto(topx,NX_MAXY(&frame) -1);
			PSstroke();

			PSnewpath();
			NXSetColor(PAScaleRGBColor(color,1.5*circleHeight));
			PSmoveto(x, NX_MAXY(&frame)-1);	PSlineto(x, NX_MAXY(&frame));
			PSmoveto(topx, NX_MAXY(&frame)-1);PSlineto(topx, NX_MAXY(&frame));
			PSstroke();
		}
	}
	else {
		rad = NX_HEIGHT(&frame)/2.0; rad2 = rad*rad;
		mid = NX_MIDY(&frame);
		for(x = NX_Y(&frame); x <= NX_MIDY(&frame); x++) {
			float topx = NX_MAXY(&frame) - (x - NX_Y(&frame));
			circleHeight = sqrt(rad2 - (mid-x)*(mid-x))/rad;

			PSnewpath();
			NXSetColor(PAScaleRGBColor(color, 1.5*circleHeight));
			PSmoveto(NX_X(&frame), x);		PSlineto(NX_X(&frame) + 2, x);
			PSmoveto(NX_X(&frame), topx);	PSlineto(NX_X(&frame) + 2, topx);
			PSstroke();

			PSnewpath();
			NXSetColor(PAScaleRGBColor(color, circleHeight));
			PSmoveto(NX_X(&frame)+2, x);	PSlineto(NX_MAXX(&frame) - 1, x);
			PSmoveto(NX_X(&frame)+2, topx);	PSlineto(NX_MAXX(&frame) - 1,topx);
			PSstroke();

			PSnewpath();
			NXSetColor(PAScaleRGBColor(color, .5*circleHeight));
			PSmoveto(NX_MAXX(&frame)-1, x);	PSlineto(NX_MAXX(&frame), x);
			PSmoveto(NX_MAXX(&frame)-1, topx);PSlineto(NX_MAXX(&frame), topx);
			PSstroke();
		}
	}

	[image unlockFocus];
        colorChanged = NO;
	return self;
}

- (const char *)getInspectorClassName { return "PAThumbWheelInspector"; }

NXColor PAScaleRGBColor(NXColor c, float scale)
{ return NXConvertRGBToColor(NXRedComponent(c)*scale, NXGreenComponent(c)*
scale, NXBlueComponent(c)*scale); }

float _IntSin[91] ={0, 0.017452406, 0.034899497, 0.052335956, 0.069756474, 
  0.087155743, 0.10452846, 0.12186934, 0.1391731, 
  0.15643447, 0.17364818, 0.190809, 0.20791169, 
  0.22495105, 0.2419219, 0.25881905, 0.27563736, 
  0.2923717, 0.30901699, 0.32556815, 0.34202014, 
  0.35836795, 0.37460659, 0.39073113, 0.40673664, 
  0.42261826, 0.43837115, 0.4539905, 0.46947156, 
  0.48480962, 0.5, 0.51503807, 0.52991926, 0.54463904, 
  0.5591929, 0.57357644, 0.58778525, 0.60181502, 
  0.61566148, 0.62932039, 0.64278761, 0.65605903, 
  0.66913061, 0.68199836, 0.69465837, 0.70710678, 
  0.7193398, 0.7313537, 0.74314483, 0.75470958, 
  0.76604444, 0.77714596, 0.78801075, 0.79863551, 
  0.80901699, 0.81915204, 0.82903757, 0.83867057, 
  0.8480481, 0.8571673, 0.8660254, 0.87461971, 
  0.88294759, 0.89100652, 0.89879405, 0.90630779, 
  0.91354546, 0.92050485, 0.92718385, 0.93358043, 
  0.93969262, 0.94551858, 0.95105652, 0.95630476, 
  0.9612617, 0.96592583, 0.97029573, 0.97437006, 
  0.9781476, 0.98162718, 0.98480775, 0.98768834, 
  0.99026807, 0.99254615, 0.9945219, 0.9961947, 
  0.99756405, 0.99862953, 0.99939083, 0.9998477, 1.};

float IntSin(int x)
{
	if(x < 0)   return -IntSin(-x);
	if(x > 180) return -IntSin(x%180);
	if(x > 90)  return  _IntSin[180-x];
	return _IntSin[x];
}
@end
